#pragma once

#include <iostream>
#include <string>
#include <cstdlib>
#include <unistd.h>
#include <strings.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

namespace ns_sock
{
    static const int g_backlog = 5;

    enum ERRNO
    {
        SOCKET_ERR = 2,
        BIND_ERR,
        LISTEN_ERR
    };

    class Sock
    {
    public:
        static int Socket() 
        {
            int sock = socket(AF_INET, SOCK_STREAM, 0);
            if(sock < 0)
            {
                std::cerr << "socket error" << std::endl;
                exit(SOCKET_ERR);
            }
            int opt = 1;
            setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));  //避免服务器挂掉再启动时无法立刻绑定端口
            return sock;
        }
        static void Bind(const int &sock, const u_int16_t &port)
        {
            struct sockaddr_in local;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(port);
            local.sin_addr.s_addr = INADDR_ANY;
            if(bind(sock, (const sockaddr*)&local, sizeof(local)) < 0)
            {
                std::cerr << "bind error" << std::endl;
                exit(BIND_ERR);
            }
        }
        static void Listen(const int& sock) 
        {
            if(listen(sock, g_backlog) < 0)
            {
                std::cerr << "listen error" << std::endl;
                exit(BIND_ERR);
            }
        }
        
    };
}